package com.soap.desensitize.strategy.irreversible;

import com.soap.desensitize.encry.irreversible.AbstractIRreversibleEncry;
import com.soap.desensitize.exception.strategy.EncodeException;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @desc	sha256加密
 * @author 	HJH
 * @time	2022-04-21
 */
public class Sha256Strategy extends AbstractIRreversibleEncry<String> {
    private static Sha256Strategy instance = null;
    private Sha256Strategy(){}

    /**
     * @desc 获得实例
     * @return
     */
    public static synchronized Sha256Strategy getInstance(){
        if(instance == null){
            instance = new Sha256Strategy();
        }
        return instance;
    }

    /**
     *
     * @param data 待加密字符串
     * @return
     * @throws NoSuchAlgorithmException
     */
    @Override
    public String encode(String data) throws EncodeException {
        //定义一个可边长的字符串
        StringBuilder sb = new StringBuilder();
        try {
            //信息摘要器                                算法名称
            MessageDigest sha256 = MessageDigest.getInstance("sha-256");
            //使用指定的字节更新摘要。
            sha256.update(data.getBytes(StandardCharsets.UTF_8));
            //把字符串转为字节数组
            byte[] bs=sha256.digest();
            // 将字节数据转换为十六进制
            for (byte b : bs) {
                sb.append(Integer.toHexString(b & 0xff));
            }

        } catch (NoSuchAlgorithmException e) {
            throw new EncodeException("加密错误，加密算法不存在");
        }
        return sb.toString();
    }
}
